import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'
import React, { Suspense, useEffect } from 'react'
import page from './page'
import Cookie from 'js-cookie'


const Router = () => {
    const BeforeEach = (props) => {

        // 获取当前路由信息
        const location = useLocation();

        // 登录拦截
        if(!Cookie.get('token') && location.pathname !== '/login') {
            // 重定向到登录页面
            return <Navigate to="/login" />
        }

        // 正常跳转
        return props.children
    }

    const renderRouter = (routes) => {
        return routes.map((item, idx) => {
            return item.path ? <Route exact key={idx} path={item.path} element={<BeforeEach>{item.element}</BeforeEach>}>
                {/* 路由子组件 */}
                {
                    item.children && renderRouter(item.children)
                }
            </Route> : <Route key={idx} path={item.from} element={<Navigate to={item.to} />} />
        })
    }

    return <Suspense fallback={<div>加载中。。。</div>}>
        <BrowserRouter>
            <Routes>
                {
                    renderRouter(page)
                }
            </Routes>
        </BrowserRouter>
    </Suspense>

}


export default Router